package com.trxy.filter;

import com.trxy.model.Customer;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/cart/*")
public class CustomerFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void destroy() {}

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)req;
        HttpSession session = request.getSession();
        Customer customer = (Customer)session.getAttribute("CUSTOMER");
        if(customer != null){ //放行
            filterChain.doFilter(req, resp);
        }else{//重定向到登录页
            HttpServletResponse response = (HttpServletResponse)resp;
            String path = request.getContextPath();
            response.sendRedirect(path + "/front/login");
        }
    }
}
